<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>this测试</title>
</head>
<body>
  <script>
    // const obj = {
    //   test: () => {
    //     console.log(this)
    //   }
    // }
    // obj.test()

    Function.prototype.bind = function (obj) {
      // var that = this
      return  () => {
        return this.call(obj)
      }
    }
    

    function fn() {
      console.log('fn', this)
    }
    const obj2 = {m: 1}
    // bind返回一个新函数, 新函数内部执行原函数, 且原函数中的this指定为obj2
    var fn3 = fn.bind(obj2)
    fn3() // 可以将来调用
    fn.call(obj2) // 立即调用
    fn()
   
    
  </script>

  <script>
    /* 相关测试题 */

    // 题1
    
    /* var a = 10
    function foo () {
      console.log(this.a)
    }
    foo()  */
   


    // 题2
    
    
   /* "use strict"   // 在严格模式下, 函数中指向window的this都为undefined
    var a = 10
    function foo () {
      console.log('this1', this)
      console.log(window.a)
      console.log(this.a) // 输出？
    }
    console.log(window.foo)
    console.log('this2', this)
    foo()  */
   

    // 题3
    
    // let/const的全局变量不会添加为window的属性
    /* let a = 10
    const b = 20

    function foo () {
      console.log(this.a)
      console.log(this.b)
    }
    foo();
    console.log(window.a)  */
   

    // 题4
    
    /* var a = 1
    function foo () {
      var a = 2
      var inner = () => { 
        console.log(a, this.a)
      }
      inner()
    }
    foo()  */
   

    // 题5
    
    /* function foo () {
      console.log(this.a)
    }
    var obj = { a: 1, foo }
    var a = 2
    obj.foo()  */
   

    // 题6
    
    /* function foo () {
      console.log(this.a)
    };
    var obj = { a: 1, foo }
    var a = 2
    var foo2 = obj.foo
    var obj2 = { a: 3, foo2: obj.foo }

    obj.foo()
    foo2()
    obj2.foo2()  */
   


    // 题7
    
    /* function foo () {
      console.log(this.a)
      return function () {
        console.log(this.a)
      }
    }
    var obj = { a: 1 }
    var a = 2

    foo() // 2
    foo.call(obj) // 1
    foo().call(obj) // 2 1 */
   


    // 题8
    
  /*  function foo () {
      console.log(this.a)
      return function () {
        console.log(this.a)
      }
    }
    var obj = { a: 1 }
    var a = 2

    foo() // 2
    foo.bind(obj) // 
    foo().bind(obj) // 2  */
   

    // 题9
    
    /* var obj = {
      name: 'obj',
      foo1: () => {
        console.log(this.name)
      },
      foo2: function () {
        console.log(this.name)
        // return function () {
        return () => {
          console.log(this.name)
        }
      }
    }
    var name = 'window'
    obj.foo1() // window
    obj.foo2()() // obj obj */
  </script>
</body>
</html>